import { useEffect, useState } from "react";
import IconFont from "@/components/IconFont";
import CommonTable from "@/components/CommonTable";
import CommonLoading from "@/components/CommonLoading";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { CloseCircleFilled } from "@ant-design/icons";
import { Button, Modal, Popover, Radio, Select, Space, message, Form, Upload } from "antd";
import { platformTypeName } from "@/utils/config";
import { handleExportExcel } from "@/utils/utils.jsx";
import useImportStore from "../../../importOrder.js";
import { find } from "lodash";
import { stringify } from "qs";
import { getCurrentUser } from "@/utils/authority";
import Style from "../index.module.less";
import Api from "../../../service.js";

const popoverProps = {
	trigger: "click",
	placement: "bottomLeft"
};

const RenderExample = ({ isSimple }) => {
	const columns = [
		{
			title: "店铺订单号",
			dataIndex: "shopOrderId"
		},
		{
			title: "商品编码",
			dataIndex: "goodsId"
		}
	];
	if (isSimple) {
		columns.push({
			title: "数量",
			dataIndex: "count"
		});
	}

	const dataSource = isSimple
		? [
				{ shopOrderId: "S00001", goodsId: "A123456", count: 1 },
				{ shopOrderId: "", goodsId: "B123456", count: 2 }
			]
		: [{ shopOrderId: "S00001", goodsId: "A123456*1，B123456*2", count: 1 }];

	const title = isSimple ? "单商品" : "多商品";
	return (
		<Popover
			content={
				<>
					<SubTitle title={title} as="s2" symbol />
					<CommonTable
						columns={columns}
						data={dataSource}
						bordered={true}
						style={{ width: isSimple ? 470 : 366, marginTop: 16, marginBottom: 8 }}
						scroll={{ x: "max-content" }}
					></CommonTable>
				</>
			}
			{...popoverProps}
		>
			<Button type="link" style={{ padding: 0 }}>
				查看示例
			</Button>
		</Popover>
	);
};

//检测文件是否发生了变更
const isFileChange = (file) => {
	return new Promise((reslove) => {
		file.slice(0,1).arrayBuffer()
		.then(() => reslove(false))
		.catch(() => reslove(true));
	})
}

const UploadExcel = ({ changeVal }) => {
	//店铺列表
	const [shopList, setShopList] = useState([]);

	const [loading, setLoading] = useState(false);

	//表单
	const [form] = Form.useForm();

	const query = useImportStore(state => state.query);

	const updateTaskId = useImportStore(state => state.updateTaskId);

	const updateQuery = useImportStore(state => state.updateQuery);

	//上传的文件列表
	const [fileList, setFileList] = useState([]);

	//初始化获取店铺列表
	useEffect(() => {
		queryShopList();
	}, []);

	//获取店铺列表
	const queryShopList = async () => {
		setLoading(true);
		const { success, data } = await Api.getStoreList();
		if (success) {
			const arr = data.filter(v => v.type != 0);
			setShopList(arr);
		}
		setLoading(false);
	};

	//选择店铺，需要判断店铺是否过期
	const handleSelect = val => {
		if (val == "all") {
			return;
		}
		const obj = find(shopList, ["id", val]);
		if (![-1, 0, 13].includes(obj.type)) {
			const nowTime = Date.now();
			//判断店铺是否过期，true: 没过期
			const isExprie = nowTime < obj.authExpireTime * 1000;
			if (!isExprie) {
				Modal.error({
					centered: true,
					title: "授权过期",
					content: `“${obj.storeName}【${platformTypeName[obj.type]}】”网店授权已过期，请先重新授权！`,
					okText: "确定",
					onOk() {
						form.resetFields(["ecStoreId"]);
					}
				});
			}
		}
	};

	//点击下载模版
	const downloadTemp = async () => {
		setLoading(true);
		const params = {
			taskType: 1001
		};
		handleExportExcel(`/blade-log/taskInfo/downloadTemplate?${stringify(params)}`, "订单表格导入模板", () => {
			setLoading(false);
		});
		setLoading(false);
	};

	//点击导入
	const onOk = async () => {
		form
			.validateFields()
			.then(val => {
				handleExport(val);
			})
			.catch(err => console.log(err));
	};

	//确定导入
	const handleExport = async val => {
		const { ecStoreId, productImportType, file } = val;
		const isChange = await isFileChange(file.file);
		if(isChange) {
			message.info('检测到上传的文件可能被修改，请重新上传文件')
			return;
		}
		const params = {
			file: file.file,
			taskType: 1001
		};
		const businessParam = {
			productImportType,
			account: getCurrentUser()?.account
		};
		//选择了店铺需要携带店铺信息
		if (ecStoreId != "all") {
			const obj = find(shopList, ["id", ecStoreId]);
			if (obj) {
				businessParam.orderChannel = obj.type;
				businessParam.storeId = obj.id;
				businessParam.ecStoreName = obj.storeName;
				businessParam.ecStoreType = 1;
			}
		}
		//需要序列化数据
		params.businessParam = JSON.stringify(businessParam);
		setLoading(true);
		const { success, data } = await Api.createImportTask(params);
		if (success) {
			updateTaskId(data);
			changeVal();
		}
		setLoading(false);
	};

	//变更导入方式
	const changeImportType = e => {
		const val = form.getFieldsValue();
		updateQuery({
			...val,
			productImportType: e.target.value
		});
	};

	const uploadProps = {
		maxCount: 1,
		accept: ".xls,.xlsx",
		onRemove: (val) => {
			setFileList([]);
		},
		beforeUpload: file => {
			//是否是表格
			const isExcel = file.name.endsWith(".xls") || file.name.endsWith(".xlsx");
			if (!isExcel) {
				message.error("只能上传excel文件!");
				return false;
			}
			//默认限制尺寸5兆
			const isLt2M = file.size / 1024 / 1024 < 3;
			if (!isLt2M) {
				message.error(`文件大小不能超过3M!`);
				return false;
			}
			setFileList([]);
			setFileList([file]);
			return false;
		},
		fileList: fileList,
		showUploadList: {
			showRemoveIcon: true,
			removeIcon: <CloseCircleFilled />
		}
	};

	//店铺下拉渲染列表
	const optionAddress = shopList.map(d => {
		return (
			<Option key={d.id} value={d.id}>
				{d.storeName}【{platformTypeName[d.type]}】
			</Option>
		);
	});

	return (
		<Space direction="vertical" size={0}>
			<SubTitle title="基本信息" as="s2" symbol />
			<Form form={form} name="order-sync-modal" initialValues={{ ...query }}>
				<Form.Item label="" name="ecStoreId" style={{ marginTop: "12px" }} rules={[{ required: true, message: "请选择网店" }]}>
					<Select
						showSearch
						style={{ width: "400px" }}
						placeholder="请选择网店"
						optionFilterProp="children"
						onSelect={handleSelect}
						allowClear
					>
						<Option key="all" value="all">
							多店铺同时导入
						</Option>
						{optionAddress}
					</Select>
				</Form.Item>

				<SubTitle title="导入商品格式" as="s2" symbol />
				<Form.Item
					label=""
					name="productImportType"
					style={{ marginTop: "12px" }}
					rules={[{ required: true, message: "请选择商品格式" }]}
				>
					<Radio.Group onChange={changeImportType}>
						<Space direction="vertical" size={0}>
							<Space size={0}>
								<Radio value={1}>单商品</Radio>
								<RenderExample isSimple={true} />
							</Space>
							<Space size={0}>
								<Radio value={2}>多商品</Radio>
								<RenderExample isSimple={false} />
							</Space>
						</Space>
					</Radio.Group>
				</Form.Item>

				<SubTitle title="上传订单表格" as="s2" symbol />

				<div className={Style["upload-box"]}>
					<Form.Item label="" name="file"  rules={[
              () => ({
                validator(rule, value) {
                  if (!value) {
                    return Promise.reject(`请上传文件`);
                  } else if (value.fileList.length == 0) {
                    return Promise.reject(`请上传文件`);
                  }
                  return Promise.resolve();
                },
              }),
            ]}>
						<Upload {...uploadProps}>
							<Button
								icon={<IconFont type="icontmpl-upload" />}
								style={{ height: 28, fontSize: "12px", display: "flex", alignItems: "center" }}
							>
								上传订单表格
							</Button>
						</Upload>
					</Form.Item>
					<Button
						className={Style["template-btn"]}
						onClick={downloadTemp}
						icon={<IconFont type="icontmpl-download" />}
						style={{ height: 28, fontSize: "12px", display: "flex", alignItems: "center" }}
					>
						下载模板
					</Button>
				</div>
				<Button type="primary" onClick={onOk} style={{ marginTop: 16 }}>
					确定导入订单
				</Button>
			</Form>
			<CommonLoading loading={loading} />
		</Space>
	);
};

export default UploadExcel;
